import { getRowByField, onArrayDataChange1 } from "@/hy_dev_lib/src"
import { DragEndEvent } from "@dnd-kit/core"
import { Input } from "antd"
import { Key, useState } from "react"
import { DEFAULT_COL_SPAN, IFormItem, IFormItemConfig } from "./type"
import { getDefaultComponentConfig } from "./utils/getComponentConfig"

const { TextArea } = Input

const useFormConfig = () => {
    const [formItemsConfig, setFormItemsConfig] = useState<IFormItemConfig[]>([])
    // 正在编辑的表单项
    const [editingItemKey, setEditingItemKey] = useState<Key>()
    const editingItem = getRowByField(formItemsConfig, editingItemKey, "name")

    // 获取表单配置数据
    const getFormItemsConfig = () => {
        // TODO: 在这里获取下拉列表等数据之后 再 setFormItemsConfig
        //  const { options } = await get("options/getOptions", { lx: formItemConfig.optionsOrigin })
        // setFormItemsConfig([])
    }

    const addFormItem = (item: IFormItem) => {
        const newItem: IFormItemConfig = {
            name: "new_item" + Math.floor(Math.random() * 100000), // 生成唯一名称
            label: "新建表单项",
            colSpan: DEFAULT_COL_SPAN,
            type: item.type,
            ...getDefaultComponentConfig(item.type),
        }
        setFormItemsConfig([...formItemsConfig, newItem])
        setEditingItemKey(newItem.name)
    }

    const editFormItem = (item: IFormItemConfig) => {
        onArrayDataChange1(formItemsConfig, setFormItemsConfig, editingItem, item, "name")
    }

    const removeFormItem = (item: IFormItemConfig) => {
        const newData = formItemsConfig.filter((j) => item.name !== j.name)
        setFormItemsConfig(newData)
    }


    const moveItem = (event: DragEndEvent) => {
        const { active, over } = event;
        if (!over?.id || active.id === over?.id) return;
        const fromIndex = formItemsConfig.findIndex(item => item.name === active.id);
        const toIndex = formItemsConfig.findIndex(item => item.name === over.id);
        const newItems = [...formItemsConfig];
        const [movedItem] = newItems.splice(fromIndex, 1);
        newItems.splice(toIndex, 0, movedItem);
        setFormItemsConfig(newItems);
    };

    return {
        formItemsConfig,
        addFormItem,
        editingItem,
        setEditingItemKey,
        editFormItem,
        moveItem,
        removeFormItem,
        getFormItemsConfig,
    }
}

export default useFormConfig;


